import {
  PageHeader,
  Steps,
  Button,
  Space,
  Form,
  Input,
  Select,
  message,
  notification,
} from 'antd'
import React, { useState, useRef, useEffect } from 'react'
import style from './index.module.scss'
import axios from 'axios'
import NewsEditor from '../../../components/NewsEditor'
import { useNavigate, useParams } from 'react-router-dom'

const { Step } = Steps

export default function NewsAdd() {
  const [currentStep, setCurrentStep] = useState(0)

  const [categoryList, setCategoryList] = useState([])

  const [formInfo, setFormInfo] = useState({})

  const [content, setContent] = useState('')
  const NewsForm = useRef(null)
  const navigateTo = useNavigate()
  const [newsInfo, setnewsInfo] = useState(null)

//   const User = JSON.parse(localStorage.getItem('xinwen-token'))
  const params = useParams()
  useEffect(() => {
    axios.get('/categories').then((res) => {
      let arr = res.data.map((item) => {
        return { ...item, label: item.value }
      })
      setCategoryList(arr)
    })
  }, [])

  useEffect(() => {
    // console.log()
    axios
      .get(`/news/${params.id}?_expand=category&_expand=role`)
      .then((res) => {
        const { title, categoryId,content } = res.data
        NewsForm.current.setFieldsValue({ title, categoryId })
        setContent(content)
      })
  }, [params.id])

  const handlerNext = () => {
    if (currentStep === 0) {
      NewsForm.current
        .validateFields()
        .then((res) => {
          setFormInfo(res)
          setCurrentStep(currentStep + 1)
        })
        .catch((err) => {})
    } else {
      if (content === '' || content.trim() === '<p></p>') {
        message.error('不能为空')
      } else {
        setCurrentStep(currentStep + 1)
      }
    }
  }
  const handlerPre = () => {
    setCurrentStep(currentStep - 1)
  }

  const handlerSave = (auditState) => {
    axios
      .patch(`/news/${params.id}`, {
        ...formInfo,
        content: content,
        auditState: auditState,
        // "publishTime": 0
      })
      .then((res) => {
        message.success('提交成功')

        let path =
          auditState === 0 ? '/news-manage/draft' : '/audit-manage/list'
        let text = auditState === 0 ? '草稿箱' : '审核列表'

        notification.open({
          message: '通知',
          description: `你可在${text}中查看`,
          placement: 'bottomRight',
        })

        navigateTo(path)
      })
      .catch((err) => {})
  }

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }

  return (
    <>
      <PageHeader
        className="site-page-header"
        onBack={() => window.history.back()}
        title="更新新闻"
      />

      <Steps current={currentStep}>
        <Step title="基本信息" description="新闻标题、分类" />
        <Step title="基本内容" description="新闻标内容" />
        <Step title="基本提交" description="保存草稿、提交" />
      </Steps>

      <div style={{ marginTop: '50px' }}>
        <div className={currentStep === 0 ? '' : style.active}>
          <Form {...layout} name="basic" ref={NewsForm}>
            <Form.Item
              label="新闻标题"
              name="title"
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="新闻分类"
              name="categoryId"
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Select
                options={categoryList}
                fieldNames={{ value: 'id' }}
                // optionLabelProp="title"
              />
            </Form.Item>
          </Form>
        </div>

        <div className={currentStep === 1 ? '' : style.active}>
          <NewsEditor
            content={content}
            getContent={(value) => {
              setContent(value)
            }}
          />
        </div>
        <div className={currentStep === 2 ? '' : style.active}>3333</div>
      </div>

      <Space style={{ marginTop: '20px' }}>
        {currentStep === 2 && (
          <>
            <Button onClick={() => handlerSave(0)}>保存草稿</Button>
            <Button onClick={handlerNext} type="dashed" danger>
              提交审核
            </Button>
          </>
        )}
        {currentStep < 2 && (
          <>
            <Button onClick={handlerNext}>下一步</Button>
          </>
        )}
        {currentStep > 0 && (
          <>
            <Button onClick={handlerPre}>上一步</Button>
          </>
        )}
      </Space>
    </>
  )
}
